package com.edu.controller;

import com.edu.bean.User;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/*
 * @Author:princess
 * @Date 2023/12/5 12 05 18:54
 *
 */
@Controller
public class UserController {
    //获取国际化文本的资源
    @Resource
    private MessageSource messageSource;

    @RequestMapping("/userLogin")
    public String userLogin(User user, Model model, Locale locale){
        if ("zhangsan".equals(user.getUsername()) && "123456".equals(user.getPassword())){
            return "index";
        }else {
            if ("zhangsan".equals(user.getUsername())){
                String msg = messageSource.getMessage("txt.passwordError",null,locale);
                model.addAttribute("msg",msg);
            }else{
                String msg = messageSource.getMessage("txt.accountError",null,locale);
                model.addAttribute("msg",msg);
            }
            return "login";
        }
    }

    @RequestMapping("/userRegister")
    public String userRegister(@Valid User user, BindingResult result, Model model, Locale locale){
        if (result.hasErrors()){
//            Map map = new HashMap();
//            List<FieldError> fieldErrors = result.getFieldErrors();
//            for (FieldError fieldError : fieldErrors) {
//                map.put(fieldError.getField(),fieldError.getDefaultMessage());
//            }
//            model.addAttribute("errors",map);
            return "register";
        }else{
            return "index";
        }
    }
}
